//
//  ProblemsHandlingViewController.m
//  Utils
//
//  Created by enghou on 2018/4/14.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "ProblemsHandlingViewController.h"
#import "PopKindsViewController.h"
#import "ProblemSearchConditionViewController.h"
#import "ProblemHandleViewController.h"
#import "ProblemHandlingItemModel.h"
#import "ProblemContainerViewController.h"
#import "ProblemDetailViewController.h"
#import "HandleHistoryViewController.h"
@interface ProblemsHandlingViewController ()
@property(nonatomic,strong)PopKindsViewController *pop;

@end

@implementation ProblemsHandlingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchAction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleProblem:) name:@"HandleProblem" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(processProblem:) name:@"ProcessProblem" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moreProblem:) name:@"MoreProblem" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(preHandleProblem:) name:@"PreHandleProblem" object:nil];
}

-(void)preHandleProblem:(NSNotification *)not{
    ProblemHandlingItemModel *model = not.object;
    [self beginLoading];
    [[NetWorkerManager sharedInstance]preHandleWithStepId:model.stepId successBlock:^(BaseModel *model) {
        [self alertSome:model.msg];
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)handleProblem:(NSNotification *)not{
    ProblemHandlingItemModel *eventId = not.object;
    ProblemContainerViewController *container = [[ProblemContainerViewController alloc]init];
    container.type = 1;
    container.eventId = eventId.ids;
    container.operations = eventId.operations;
    container.stepId = eventId.stepId;
    [self push:container];
}

-(void)processProblem:(NSNotification *)not{
    ProblemHandlingItemModel *item = not.object;
    HandleHistoryViewController *handle = [[HandleHistoryViewController alloc]init];
    handle.event_id = item.ids;
    handle.type = self.type;
    if (self.type == 0) {
        handle.modelClsName = @"HandleHistoryItemModel";
        handle.path = kHandleHistory;
    }else{
        handle.modelClsName = @"AppealHandleHistoryItemModel";
        handle.path = @"/mobile/comprehensiveGovernance/appeal/getProcessDescriptionByAppealId.action";
    }
    handle.cellClass = @"HandleHistoryCellTableViewCell";
    [self push:handle];
}

-(void)moreProblem:(NSNotification *)not{
    //如何处理更多
    //各种督办
    typedef void(^ForceHandling)(ProblemHandlingItemModel *,NSString *code);
     ForceHandling redCard = ^(ProblemHandlingItemModel *model,NSString *code){
        [self forceDoneWithItem:model code:code];
    };
    typedef void(^HandleProblem)(ProblemHandlingItemModel *);
    HandleProblem urgent = ^(ProblemHandlingItemModel *model){
        [self urgentWithItem:model];
    };
    HandleProblem deleteAct = ^(ProblemHandlingItemModel *model){
        [self deleteAnItemWithModel:model];
    };
    HandleProblem leaderSpeak = ^(ProblemHandlingItemModel *model){
        [self leaderSpeakWithItem:model];
    };
    HandleProblem becomeHistory = ^(ProblemHandlingItemModel *model){
        [self becomeHistoryWithItem:model];
    };
    HandleProblem modify = ^(ProblemHandlingItemModel *model){
        [self modifyItem:model];
    };
    NSDictionary *compare = @{@"redCardIssue":redCard,@"normalIssue":redCard,@"yellowCardIssue":redCard,@"urgentIssue":urgent,@"commandIssue":leaderSpeak,@"deleteIssue":deleteAct,@"updateIssue":modify,@"historicalIssue":becomeHistory};
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSDictionary *param in self.permissions) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:param[@"value"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *key = param[@"key"];
            if ([key isEqualToString:@"redCardIssue"]) {
                ForceHandling result = compare[key];
                result(not.object,@"86");
            }else if ([key isEqualToString:@"yellowCardIssue"]){
                ForceHandling result = compare[key];
                result(not.object,@"83");
            }else if ([key isEqualToString:@"normalIssue"]){
                ForceHandling result = compare[key];
                result(not.object,@"81");
            }else{
                HandleProblem result = compare[key];
                result(not.object);
            }
        }];
        [alert addAction:action];
    }
    UIAlertAction *calcel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:calcel];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)deleteAnItemWithModel:(ProblemHandlingItemModel *)model{
    //删除一条
    [self beginLoading];
    [[NetWorkerManager sharedInstance]deleteProblemWithPid:model.ids successBlock:^(BaseModel *model) {
        [self endLoading];
        if (model.success) {
            [self beginRefresh];
        }else{
            [self alertSome:model.msg];
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)modifyItem:(ProblemHandlingItemModel *)model{
    //修改一条
}

-(void)urgentWithItem:(ProblemHandlingItemModel *)model{
    //加急一条
    [self alertSome:@"加急意见" key:@"logNew.content" sureAction:^(NSDictionary *param) {
        NSMutableDictionary *p = [NSMutableDictionary dictionaryWithDictionary:param];
        [p setObject:model.stepId forKey:@"issueStepId"];
        [self beginLoading];
        [[NetWorkerManager sharedInstance]commonAlertInterfaceWithPath:kProblemForceFast parameter:p successBlock:^(BaseModel *model) {
            [self endLoading];
            [self alertSome:model.msg];
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }];
}

-(void)leaderSpeakWithItem:(ProblemHandlingItemModel *)model{
    //领导批示
    [self alertSome:@"领导批示" key:@"logNew.content" sureAction:^(NSDictionary *param) {
        NSMutableDictionary *p = [NSMutableDictionary dictionaryWithDictionary:param];
        [p setObject:model.stepId forKey:@"issueStepId"];
        [self beginLoading];
        [[NetWorkerManager sharedInstance]commonAlertInterfaceWithPath:kProblemLeaderSpeak parameter:p successBlock:^(BaseModel *model) {
            [self endLoading];
            [self alertSome:model.msg];
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }];
}

-(void)forceDoneWithItem:(ProblemHandlingItemModel *)model code:(NSString *)code{
    //根据督办类型督办
    NSString *msg;
    if ([code isEqualToString:@"81"]) {
        msg = @"普通督办";
    }else if ([code isEqualToString:@"83"]){
        msg = @"黄牌督办";
    }else if ([code isEqualToString:@"86"]){
        msg = @"红牌督办";
    }
    [self alertSome:msg key:@"logNew.content" sureAction:^(NSDictionary *param) {
        NSMutableDictionary *p = [NSMutableDictionary dictionaryWithDictionary:param];
        [p setObject:model.stepId forKey:@"issueStepId"];
        [p setObject:code forKey:@"operationCode"];
        [self beginLoading];
        [[NetWorkerManager sharedInstance]commonAlertInterfaceWithPath:kProblemForceResolve parameter:p successBlock:^(BaseModel *model) {
            [self endLoading];
            [self alertSome:model.msg];
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }];
}

-(void)becomeHistoryWithItem:(ProblemHandlingItemModel *)model{
    //成为历史遗留
    [self beginLoading];
    [[NetWorkerManager sharedInstance]commonAlertInterfaceWithPath:kProblemBecomeHistory parameter:@{@"issueStepId":model.stepId} successBlock:^(BaseModel *model) {
        [self endLoading];
        [self alertSome:model.msg];
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)alertSome:(NSString *)msg key:(NSString *)key sureAction:(void (^)(NSDictionary *))act{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:msg message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
    }];
    UIAlertAction *sureAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        act(@{key:alert.textFields[0].text});
    }];
    [alert addAction:sureAct];
    UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancelAct];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

-(NSDictionary *)compareItem{
    NSDictionary *compare = @{@"redCardIssue":@"红牌督办",@"normalIssue":@"普通督办",@"yellowCardIssue":@"黄牌督办",@"urgentIssue":@"加急",@"commandIssue":@"领导批示",@"deleteIssue":@"删除",@"updateIssue":@"修改",@"historicalIssue":@"历史遗留"};
    return compare;
}

-(void)refreshSuccessWithModel:(BaseModel *)model{
    NSDictionary *permission = [model.data[@"data"] objectForKey:@"permission"];
    NSDictionary *compare = [self compareItem];
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in permission.allKeys) {
        BOOL result = [permission[key] boolValue];
        if (result) {
            NSString *value = compare[key];
            if (value) {
                NSDictionary *param = @{@"key":key,@"value":value};
                [array addObject:param];
            }
        }
    }
    self.permissions = array;
    for (ProblemHandlingItemModel *m in model.list) {
        m.state = self.type;
    }
    self.source = [model.list mutableCopy];
    self.page = 1;
    NSDictionary *data = [model.data objectForKey:@"data"];
    if ([[data allKeys]containsObject:@"records"]) {
        NSInteger records = [[data objectForKey:@"records"]integerValue];
        self.totalRecords = records;
    }
    if ([self.source count] == self.totalRecords) {
        self.full = YES;
    }else{
        self.full = NO;
    }
    if ([self.source count] == 0) {
        self.full = NO;
    }
    [self.tableView reloadData];
}

-(void)loadMoreSuccessWithModel:(BaseModel *)model{
    for (ProblemHandlingItemModel *m in model.list) {
        m.state = self.type;
    }
    NSDictionary *data = [model.data objectForKey:@"data"];
    if ([[data allKeys]containsObject:@"records"]) {
        NSInteger records = [[data objectForKey:@"records"]integerValue];
        self.totalRecords = records;
    }
    if ([model.list count] == 0) {
        self.full = YES;
        return;
    }else{
        self.page++;
        [self.source addObjectsFromArray:model.list];
        if ([self.source count] == self.totalRecords) {
            self.full = YES;
        }
        [self.tableView reloadData];
    }
}

-(NSDictionary *)param{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([self.eventName length] > 0) {
        [param setObject:self.eventName forKey:@"searchIssueVo.name"];
    }
    if ([self.scaleId length] > 0) {
        [param setObject:self.scaleId forKey:@"searchIssueVo.issueKind.id"];
    }
    if ([self.eventSource length] > 0) {
        [param setObject:self.eventSource forKey:@"searchIssueVo.eventSource.id"];
    }
    if ([self.beginTime length] > 0) {
        [param setObject:self.beginTime forKey:@"searchIssueVo.entryTimeStart"];
    }
    if ([self.endTime length] > 0) {
        [param setObject:self.endTime forKey:@"searchIssueVo.entryTimeEnd"];
    }
    if ([self.typeId length] > 0) {
        [param setObject:self.typeId forKey:@"searchIssueVo.issueTypeId"];
    }
    return param;
}

-(void)searchAction{
    ProblemSearchConditionViewController *problem = (ProblemSearchConditionViewController *)[VCLoader vcWithName:@"ProblemSearchConditionViewController"];
    problem.theDelete = self;
    [self push:problem];
}

-(void)switchType:(NSInteger)type button:(UIButton *)titleButton{
    switch (type) {
        case 0:
        {
            self.path = kProblemPending;
            [self beginRefresh];
            [titleButton setTitle:@"矛盾纠纷-待办" forState:UIControlStateNormal];
        }
            break;
        case 1:
        {
            self.path = kProblemDone;
            [self beginRefresh];
            [titleButton setTitle:@"矛盾纠纷-已办" forState:UIControlStateNormal];
        }
            break;
        case 2:
        {
            self.path = kProblemDone;
            [self beginRefresh];
            [titleButton setTitle:@"矛盾纠纷-办结" forState:UIControlStateNormal];
        }
            break;
        case 3:
        {
            self.path = kProblemSubPending;
            [titleButton setTitle:@"矛盾纠纷下辖-待办" forState:UIControlStateNormal];
            [self beginRefresh];
        }
            break;
        case 4:
        {
            self.path = kProblemSubDone;
            [titleButton setTitle:@"矛盾纠纷下辖-办结" forState:UIControlStateNormal];
            [self beginRefresh];
        }
            break;
        case 5:
        {
            self.path = kProblemHistory;
            [titleButton setTitle:@"历史遗留" forState:UIControlStateNormal];
            [self beginRefresh];
        }
            break;
        default:
            break;
    }
    self.titles = @[@"矛盾纠纷-待办",@"矛盾纠纷-已办",@"矛盾纠纷下辖-待办",@"矛盾纠纷下辖-办结",@"历史遗留"];
}

-(void)setType:(NSInteger)type{
    _type = type;
    UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    titleButton.frame = CGRectMake(0, 0, 200, 40);
    UIImage *image = [[UIImage imageNamed:@"icon_drop"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [titleButton setImage:image forState:UIControlStateNormal];
    UIGraphicsBeginImageContextWithOptions(image.size, NO, [[UIScreen mainScreen]scale]);
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, image.size.height);
    CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1, -1);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    UIImage *mirroredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [titleButton setImage:mirroredImage forState:UIControlStateSelected];
    [self switchType:type button:titleButton];
    [titleButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -titleButton.imageView.frame.size.width, 0, titleButton.imageView.frame.size.width)];
    [titleButton setImageEdgeInsets:UIEdgeInsetsMake(0, titleButton.titleLabel.bounds.size.width, 0, -titleButton.titleLabel.bounds.size.width)];
    [titleButton addTarget:self action:@selector(chooseType:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
}

-(void)chooseType:(UIButton *)button{
    button.selected = !button.selected;
    if (!self.presentedViewController) {
        if (!self.pop) {
            self.pop = [[PopKindsViewController alloc]init];
            self.definesPresentationContext = YES;
            self.pop.theDelete = self;
            self.pop.selectedIndex = self.type;
            self.pop.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            self.pop.titles = self.titles;
        }
        [self presentViewController:self.pop animated:NO completion:nil];
    }else{
        [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ProblemHandlingItemModel *model = [self.source objectAtIndex:indexPath.row];
    ProblemDetailViewController *detail = (ProblemDetailViewController *)[VCLoader vcWithName:@"ProblemDetailViewController"];
    detail.detail_id = model.ids;
    detail.stepId = model.stepId;
    detail.statusCode = model.stepStatusCode;
    [self push:detail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
